﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HtmlExtractor.Processor;
using System.Xml.Linq;

namespace HtmlExtractor.Config
{
    public class Simple:IPageItemConfig
    {

        //private readonly ILog log = LogManager.GetLogger(typeof(Simple));
        public string Name
        { get; set; }

        public IEnumerable<ReplaceExpression> ReplaceExpressions;
        public RegexConfig Regex
        {
            get;
            set;
        }
        public string OutputPath;
        public RegexConfig ValidExpression;
        public RegexConfig SplitExpression;
        public string PreProcessorName;
        /// <summary>
        /// 如果有多个匹配，对每个匹配都执行
        /// </summary>
        public string PostProcessorName;
        public string OutputProcessorName;
        /// <summary>
        /// 如果有多个匹配，对每个匹配都执行SubRule
        /// </summary>
        public IPageItemConfig SubRule
        {
            get;
            set;
        }
        public Simple()
        { }
      
        protected virtual void InitSimple(XElement simpleNode)
        {
            if (simpleNode == null)
                throw new RequierdNotFindException(RequriedType.Element,"simpleNode");
            if (simpleNode != null)
            {
                Name = (string)simpleNode.Attribute("name");
                OutputPath = (string)simpleNode.Attribute("outputPath");               
                Regex = new RegexConfig(simpleNode.Element("Regex"));
                ValidExpression = simpleNode.Element("ValidExpression") == null ? null :new RegexConfig(simpleNode.Element("ValidExpression"));
                SplitExpression = simpleNode.Element("SplitExpression") == null ? null : new RegexConfig(simpleNode.Element("SplitExpression"));
                ReplaceExpressions = from r in simpleNode.Elements("ReplaceExpression")
                                     select ReplaceExpression.Create(r);
                    //simpleNode.Element("ReplaceExpression") == null ? null : ReplaceExpression.Create(simpleNode.Element("ReplaceExpression"));
                OutputProcessorName = (string)simpleNode.Element("Output");
                PreProcessorName = (string)simpleNode.Element("PreProcessor");
                PostProcessorName = (string)simpleNode.Element("PostProcessor");
                Assert.IsNullOrEmpty(Regex.Expression);
                XElement sub = simpleNode.Element("Sub");
                if (sub != null)
                {
                   SubRule = RuleBuildFactory.Create(sub.Elements().Single());
                }              
               
            }          
        }
        public Simple(XElement simpleNode)
        {
            InitSimple(simpleNode);  
        }
        //simple group 处理混在一起了
        internal PageResult GetParsResult(string text, GroupInfoCollection GroupInfos, ParserContext context)
        {
            bool isSimpleRule = true;
            if (GroupInfos != null)
            { isSimpleRule = false; }
            PageResult result = new PageResult();
            result.OutputProcessorName = OutputProcessorName;
            string temp = text;
            if (!string.IsNullOrEmpty(PreProcessorName))
            {
                temp = ProcessorFactory.CreateProcessor(PreProcessorName).GetResult(text,context);
            }
            SegmentCollection segments = SegmentRegex.Match(temp, Regex.Expression, Regex.Options, true);
            foreach (Segment s in segments)
            {
                if (s.Match != null)
                {

                    string postValue = s.Value;
                    if (isSimpleRule)
                    {
                        if (s.Match.MatchGroups.Count != 0)
                        {
                            //log.Info(Regex.Expression + "包含捕获组，捕获组在Simple规则不被处理，如果处理组使用Group规则");
                           // throw new ApplicationException(Regex.Expression + "包含捕获组，捕获组在Simple规则不被处理，如果处理组使用Group规则");
                        }
                    }
                    else
                    {
                        if (s.Match.MatchGroups.Count != 0)
                        {
                            //处理group
                            result.AddRange(GroupInfos.GetParseResult(s.Match.MatchGroups, context));
                        }
                    }
                    if (!string.IsNullOrEmpty(PostProcessorName))
                    {
                        postValue = ProcessorFactory.CreateProcessor(PostProcessorName).GetResult(postValue,context);
                    }
                    if (!string.IsNullOrEmpty(OutputPath))
                    {
                        result.Add(new SimpleItem(OutputPath, postValue));
                    }
                    if (ValidExpression != null)
                    {
                        //todo valid
                    }
                    if (ReplaceExpressions != null)
                    {
                        foreach (ReplaceExpression re in ReplaceExpressions)
                        {
                            postValue = re.GetResult(postValue, context);
                        }
                    }
                    if (SubRule != null)
                    {
                        PageResult subResult = SubRule.GetParseResult(postValue, context);
                        result.AddRange(subResult);
                    }
                }
            }
            return result;
        }
        #region IRule 成员

        public virtual PageResult GetParseResult(string text,ParserContext context)
        {
            return GetParsResult(text, null,context);         
          
           
        }

        #endregion
    }
}
